package com.igroupes.ovineherd.handler;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Administrator
 * @title: JSONObjectTypeHandler
 * @projectName ovineherd-parent
 * @description: TODO
 * @date 2020/12/1217:57
 */
@MappedTypes(JSONObject.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class JSONObjectTypeHandler extends BaseTypeHandler<JSONObject> {
    private String toJsonString(JSONObject jsonObject) {
        return null != jsonObject && !"".equals(jsonObject.toString()) ? JSONUtil.toJsonStr(jsonObject) : null;
    }
    private JSONObject parse(String json) {
        return json != null && json.length() != 0 ? JSONUtil.parseObj(json) : null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, JSONObject jsonObject, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, this.toJsonString(jsonObject));
    }

    @Override
    public JSONObject getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return parse( resultSet.getString(s));
    }

    @Override
    public JSONObject getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return parse( resultSet.getString(i));
    }

    @Override
    public JSONObject getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return parse( callableStatement.getString(i));
    }
}
